package com.olmarket.core.util;

import java.util.*;

/**
 * @author: qwesde@hust.edu.cn
 * @date: 2021/3/1 20:22
 */
public class GraphUtil {
    public static class Edge {
        public int x, y;

        public Edge(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }


    /**
     * 使用拓扑排序 检查一个图是不是存在环
     *
     * @param edges 邻接表存的图
     * @return true, having circle or not
     */
    public static boolean CircleCheck(List<Edge> edges) {
        Queue<Integer> que = new LinkedList<>();
        Map<Integer, Integer> map = new HashMap<>();
        Set<Integer> points = new TreeSet<>();
        Map<Integer, ArrayList<Integer>> vec = new HashMap<>();

        for (Edge e : edges) {
            map.put(e.y, map.getOrDefault(e.y, 0) + 1);
            points.add(e.x);
            points.add(e.y);

            ArrayList<Integer> tmp = vec.getOrDefault(e.x, new ArrayList<>());
            tmp.add(e.y);
            vec.put(e.x, tmp);
        }

        for (int x : points) {
            if (map.getOrDefault(x, 0) == 0) {
                que.add(x);
            }
        }
        int count = 0;
        while (!que.isEmpty()) {
            int x = que.poll();
            count++;
            for (int v : vec.getOrDefault(x, new ArrayList<Integer>())) {
                int d = map.getOrDefault(v, 0);
                if (d > 0) {
                    map.put(v, --d);
                    if (d == 0) {
                        que.add(v);
                    }
                }
            }
        }
        return points.size() != count;
    }
}
